package com.example.cart_system.service.Impl;

import com.example.cart_system.jwt.JwtUtil;
import com.example.cart_system.mapper.UsrMapper;
import com.example.cart_system.pojo.*;
import com.example.cart_system.service.UsrService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class UsrServiceImpl implements UsrService {
    @Autowired
    private UsrMapper usrMapper;
    @Override
    public boolean register(Usr usr) {
        String name = usrMapper.getUsrName(usr.getUsrname());
        if (name != null) {
            return false;
        }
        Instant now = Instant.now();
        usr.setUsrid(String.valueOf(now.toEpochMilli()));
        usr.setUsrcorn(1000);
        usr.setUsrplayer(1);
        usr.setCreateTime(LocalDateTime.now());
        System.out.println(usr);
        usrMapper.insertUsr(usr);
        return true;
    }

    @Override
    public UsrInfo login(Usr usr) {
        Usr user = usrMapper.selectByUsrnameAndUsrpassword(usr);
        if (user != null) {
            usrMapper.updateUsrLoginTime(user.getUsrid(), LocalDateTime.now());
            String token = JwtUtil.generateToken(usr.getUsrname(), usr.getUsrid());
            UsrInfo usrInfo = new UsrInfo(user.getUsrid(), user.getUsrname(), token);
            usrInfo.setUsrCorn(user.getUsrcorn());
            usrInfo.setUsrPlayer(user.getUsrplayer());
            return usrInfo;
        }
        return null;
    }

    @Override
    public void buy(Order order) {
        order.setOid(String.valueOf(System.currentTimeMillis()));
        order.setOtime(LocalDateTime.now());
        usrMapper.buy(order);
    }

    @Override
    public List<Usr> selectAllUsrName() {
        return usrMapper.selectAllUsrName();
    }
}
